package com.xcyy.clbzbh.controller;

import com.xcyy.clbzbh.VO.QueryParam;
import com.xcyy.clbzbh.VO.ResultVO;
import com.xcyy.clbzbh.common.ResultVOUtil;
import com.xcyy.clbzbh.entity.*;
import com.xcyy.clbzbh.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


@RestController
public class MyPointsController {
    @Autowired
    private BenchmarkService benchmarkService;
    @Autowired
    private GPSPointService gpsPointService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Value("${uploadPath}")
    String realPath;


    @PostMapping("/findmypoints")
    public ResultVO findAll(@RequestParam(value = "pointid", required = false) String pointid
            , @RequestParam(value = "name", required = false) String name
            , @RequestParam(value = "grade", required = false) String grade
            , String username, String type, Integer pageNum, Integer pageSize) {
        //Pageable pageable=PageRequest.of(pageNum,pageSize, Sort.by(Sort.Direction.ASC,"pointID"));
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        QueryParam queryParam = new QueryParam(name, pointid, grade);
        //查询user
        User user = userService.findByUsername(username);
        //查询角色
        UserRole userRole = userRoleService.findByUserId(user.getId());

        if ("2".equals(userRole.getRoleId())) {
            queryParam.setCity(user.getCity());
        } else if ("1".equals(userRole.getRoleId())) {
            queryParam.setCity(user.getCity());
            queryParam.setCountry(user.getCountry());
        }

        if ("gpspoint".equals(type)) {
            Page<GPSPoint> gpsPoints;
            gpsPoints = gpsPointService.findAll(queryParam, pageNum - 1, pageSize);
            return ResultVOUtil.successforCount(gpsPoints.getContent(), gpsPoints.getTotalElements());
        }
        if ("benchmark".equals(type)) {
            Page<Benchmark> benchmarks;
            benchmarks = benchmarkService.findAll(queryParam, pageNum - 1, pageSize);
            return ResultVOUtil.successforCount(benchmarks.getContent(), benchmarks.getTotalElements());
        }
        return ResultVOUtil.error(400, "type error!");
    }

    @PostMapping("/findpoints")
    public ResultVO findPoints(String type ,String username){
        //查询user
        User user = userService.findByUsername(username);
        if ("gpspoint".equals(type)) {
            List<GPSPoint> gpsPoints=gpsPointService.findByCountry(user.getCountry());
            return ResultVOUtil.success(gpsPoints);
        }
        if ("benchmark".equals(type)) {
            List<Benchmark> benchmarks=benchmarkService.findByCountry(user.getCountry());
            return ResultVOUtil.success(benchmarks);

        }
        return ResultVOUtil.error(400, "type error!");
    }

    @PostMapping("/updatebenchmark")
    public ResultVO updateBenchmark(Benchmark benchmark
            , @RequestParam(value = "imagepanorama", required = false) MultipartFile imagePanorama
            , @RequestParam(value = "imagebust", required = false) MultipartFile imageBust
            , @RequestParam(value = "imagecloseup", required = false) MultipartFile imageCloseup) throws IOException {
        benchmark.setPanorama(null);
        benchmark.setBust(null);
        benchmark.setCloseup(null);
        Benchmark result = benchmarkService.findById(benchmark.getId());
        if (result != null) {

            File folder = new File(realPath + result.getPointID() + "-" + result.getName());
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            if (imagePanorama != null) {
                benchmark.setPanorama( "/"+result.getPointID() + "-" + result.getName()+"/"+updatePic(imagePanorama, folder, result.getPointID() + "_" + result.getName() + "_panorama"));
            }
            if (imageBust != null) {
                benchmark.setBust("/"+result.getPointID() + "-" + result.getName()+"/"+updatePic(imageBust, folder, result.getPointID() + "_" + result.getName() + "_bust"));
            }
            if (imageCloseup != null) {
                benchmark.setCloseup("/"+result.getPointID() + "-" + result.getName()+"/"+updatePic(imageCloseup, folder, result.getPointID() + "_" + result.getName() + "_closeup"));
            }
            benchmark.setStatus("已提交");
            result = benchmarkService.save(benchmark);
            return ResultVOUtil.success(result);
        } else {
            return ResultVOUtil.error(404, "id不存在");
        }
    }

    private String updatePic(MultipartFile file, File folder, String fix) throws IOException {

        // 获取文件名
        String name = file.getOriginalFilename();
        //判断是否为IE浏览器的文件名，IE浏览器下文件名会带有盘符信息
        // Check for Unix-style path
        int unixSep = name.lastIndexOf('/');
        // Check for Windows-style path
        int winSep = name.lastIndexOf('\\');
        // Cut off at latest possible point
        int pos = (winSep > unixSep ? winSep : unixSep);
        if (pos != -1) {
            // Any sort of path separator found...
            name = name.substring(pos + 1);
        }
        //String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        name = fix + name.substring(name.lastIndexOf("."));
        file.transferTo(new File(folder, name));

        return name;

    }

    @PostMapping("/updategpspoint")
    public ResultVO updateGPSPoint(GPSPoint gpsPoint
            , @RequestParam(value = "imagepanorama", required = false) MultipartFile imagePanorama
            , @RequestParam(value = "imagebust", required = false) MultipartFile imageBust
            , @RequestParam(value = "imagecloseup", required = false) MultipartFile imageCloseup) throws IOException {
        gpsPoint.setPanorama(null);
        gpsPoint.setBust(null);
        gpsPoint.setCloseup(null);
        GPSPoint result = gpsPointService.findById(gpsPoint.getId());
        if (gpsPoint.getId() != null) {
            File folder = new File(realPath + result.getPointID() + "-" + result.getName());
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            if (imagePanorama != null) {
                gpsPoint.setPanorama("/"+result.getPointID() + "-" + result.getName()+"/"+updatePic(imagePanorama, folder, result.getPointID() + "_" + result.getName() + "_panorama"));
            }
            if (imageBust != null) {
                gpsPoint.setBust("/"+result.getPointID() + "-" + result.getName()+"/"+updatePic(imageBust, folder, result.getPointID() + "_" + result.getName() + "_bust"));
            }
            if (imageCloseup != null) {
                gpsPoint.setCloseup("/"+result.getPointID() + "-" + result.getName()+"/"+updatePic(imageCloseup, folder, result.getPointID() + "_" + result.getName() + "_closeup"));
            }
            gpsPoint.setStatus("已提交");
            result = gpsPointService.save(gpsPoint);
            return ResultVOUtil.success(result);
        } else {
            return ResultVOUtil.error(404, "id不存在");
        }
    }

}
